<template>
  <TableView class="table">
    <template #table>
      <div style="background-color: #ebeceb; width: 100%; height: 100%; padding: 10rem">
        <NSpin :show="spinShow">
          <n-calendar :theme-overrides="cellModalTheme" @panel-change="handlePanelChange">
            <template #default="{ year, month, date }">
              <div class="main" @click="goToInfo(year, month, date)">
                <div class="topNave">{{ date }}</div>
                <div class="content" v-if="handlePeopleStatus(year, month, date, 'morningAttendanceStatus') == '休息' &&
                  handlePeopleStatus(year, month, date, 'afternoonAttendanceStatus') == '休息'">
                  <div style="display: flex;justify-content: center;align-items: center;height:100%;">休息</div>
                </div>
                <div class="content" v-else>
                  <!-- 上午 -->
                  <div class="content_box" :style="{
                    backgroundColor: handleTdColor(year, month, date, 'morningAttendanceStatus'),
                    borderTop: handleBorderTop(year, month, date, 'morningAttendanceStatus')
                  }">
                    <div>
                      {{ handlePeopleStatus(year, month, date, 'morningAttendanceStatus') }}
                    </div>
                    <div>{{ handlePeopleStatus(year, month, date, 'realityStartWorkTime') }}</div>
                  </div>
                  <!-- 下午 -->
                  <div class="content_box" :style="{
                    backgroundColor: handleTdColor(year, month, date, 'afternoonAttendanceStatus'),
                    borderTop: handleBorderTop(year, month, date, 'morningAttendanceStatus')
                  }">
                    <div>
                      {{ handlePeopleStatus(year, month, date, 'afternoonAttendanceStatus') }}
                    </div>
                    <div>{{ handlePeopleStatus(year, month, date, 'realityEndWorkTime') }}</div>
                  </div>
                </div>
              </div>
            </template>
          </n-calendar>
        </NSpin>
      </div>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <ModalCard title="详情" @close="modalVisible = false">
      <div style="padding: 24rem">
        <VMineAttendanceInfo :timeDate="timeDate" @close="modalVisible = false" />
      </div>
    </ModalCard>
  </NModal>
</template>

<script setup lang="ts">
import { useMessage, NCalendar, NSpin, NModal } from 'naive-ui'
import { ref, onMounted, render, h } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { AttendanceModel } from '@/api/attendance'
import type { HttpResponse } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VContent from '@/views/OA/Office/components/WeekContent.vue'
import ModalCard from '@/components/ModalCard.vue'
import VMineAttendanceInfo from './components/MineAttendanceInfo.vue'

const message = useMessage()
const route = useRoute()
const cellModalTheme = { cellColorHover: 'none', barColor: 'none', borderColor: 'black' }

// 去详情
const modalVisible = ref(false)
const timeDate = ref()
const goToInfo = (year: any, month: any, date: any) => {
  timeDate.value =
    year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
  modalVisible.value = true
}
// 页码切换
const handlePanelChange = (info: { year: number; month: number }) => {
  const month = info.year + '-' + (Number(info.month) < 10 ? '0' + info.month : info.month)
  getOverTimeList(month)
}
// 查询人数
const handlePeopleStatus = (year: any, month: any, date: any, c: any) => {
  if (!tableData.value) return
  const timeDate =
    year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
  let result = null
  let timeMonth = null
  const key = tableData.value.findIndex((it: any) => it.date?.split(' ')[0] == timeDate)
  if (key != -1 && tableData.value[key]) {
    timeMonth = tableData.value[key]['date'].split(' ')[0].split('-')
    timeMonth = timeMonth[0] + '-' + timeMonth[1]
    if (tableData.value[key][c]) result = tableData.value[key][c]
    if ((c == 'realityStartWorkTime' && tableData.value[key]['rest']) ||
      (c == 'realityEndWorkTime' && tableData.value[key]['rest']))
      result = result ? '(' + result?.split(' ')[1] + ')' : result
  }
  // if (['周六', '周日'].includes(getWeekDay(timeDate)) && !result && !['realityStartWorkTime', 'realityEndWorkTime'].
  //   includes(c) && (year + '-' + (month < 10 ? '0' + month : month) == timeMonth)) {
  //   result = '休息'
  // }
  if (key != -1 && !tableData.value[key]['rest'] && (!tableData.value[key]['morningAttendanceStatus'] &&
    c == 'morningAttendanceStatus')) result = '休息'
  if (key != -1 && !tableData.value[key]['rest'] && (!tableData.value[key]['afternoonAttendanceStatus'] &&
    c == 'afternoonAttendanceStatus')) result = '休息'
  return result
}
// 根据日期判断周几
const getWeekDay = function (time: string) {
  let datelist = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return datelist[new Date(time).getDay()]
}
// 判断背景色
const handleTdColor = (year: any, month: any, date: any, c: any) => {
  if (!tableData.value) return
  const timeDate =
    year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
  let result = null
  const key = tableData.value.findIndex((it: any) => it.date?.split(' ')[0] == timeDate)
  if (key != -1 && tableData.value[key]) result = tableData.value[key][c]
  if (result == '出差') return '#bb89b1'
  if (result == '迟到' || result == '早退') return '#d4ab70'
  if (result == '公出') return '#88daff'
  if (result == '加班') return '#44daff'
  if (result == '旷') return '#ff6944'
  if (result == '正常') return '#fff'
  else if (result) return '#8f82c1'
}
// 判断表变
const handleBorderTop = (year: any, month: any, date: any, c: any) => {
  if (!tableData.value) return
  const timeDate =
    year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
  let result = null
  const key = tableData.value.findIndex((it: any) => it.date?.split(' ')[0] == timeDate)
  if (key != -1 && tableData.value[key]) result = tableData.value[key][c]
  if (result == '正常') return '2.5px solid black'
  else return 'none'
}
// 获取列表
const spinShow = ref(false)
const tableData = ref()
const getOverTimeList = async (month: any) => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse<AttendanceModel>>({
    module: 'attendance',
    api: 'getUserMonthWorkAttendanceList',
    override: {
      params: {
        month,
        userId: route.query.userId
      }
    }
  })
  spinShow.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data
}
// 创建子节点
const handleWeek = () => {
  const A = document.querySelector('.n-calendar')
  const B = document.querySelector('.n-calendar-dates')
  const C = document.createElement('div')
  render(h(VContent, { BgcColor: 'black' }), C)
  A?.insertBefore(C, B)
}

onMounted(() => {
  handleWeek()
  const date = new Date().toLocaleDateString().split('/')
  const month = date[0] + '-' + (Number(date[1]) < 10 ? '0' + date[1] : date[1])
  getOverTimeList(month)
})
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}

:deep(.n-calendar) {
  width: 100%;
  height: 100%;
}

::v-deep(.n-calendar-cell) {
  display: flex;
  flex-direction: column;
  cursor: auto;
  padding: 0;

  .n-calendar-date {
    display: none;

    .n-calendar-date__date {
      display: none;
    }
  }

  .main {
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;

    .topNave {
      width: 100%;
      flex: 0 0 20%;
      text-align: right;
      padding: 5rem;
      font-size: 20rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      flex: 1;
      font-size: 18rem;

      .content_box {
        flex: 0 0 50%;
        display: flex;
        justify-content: center;
        align-items: center;

        div {
          width: auto;
        }
      }
    }
  }
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

::v-deep(.n-calendar-cell--current .n-calendar-date .n-calendar-date__date) {
  background-color: transparent !important;
  color: black !important;
}
</style>
